package com.chenchao.thread;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/16 15:41
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javathread.Test3.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 加锁
 */
public class Test3 {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new RunImpl());
        Thread thread2 = new Thread(new RunImpl());
        Thread thread3 = new Thread(new RunImpl());
        thread1.start();
        thread2.start();
        thread3.start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                RunImpl run = new RunImpl();
                while (true){
                    run.g();
                }
            }
        }).start();



    }
}

class RunImpl implements Runnable {
    private static int TricketNum = 1000;

    @Override
    public void run() {
        while (true) {
            synchronized (RunImpl.class) {
                //个人理解：执行{}中的代码时，对（）中的东西加锁
                //加锁的东西必须是唯一的
                //对象锁：this指代的是当前对象，限制同一个对象的多线程
                //类锁：RunImpl.class锁的是这个类的类对象，限制同一个类的对象之间的多线程

                if (TricketNum > 0) {
                    TricketNum--;
                    System.out.println("还剩票" + TricketNum + "张");
                } else {
                    System.out.println("票已经售完！");
                    System.exit(0);
                }
            }
        }

    }

    /**
     * 也可以用synchronized修饰符对方法进行加锁调用
     * 静态方法加锁相当于类锁
     * 非静态方法加锁相当于对象锁
     */
    public synchronized static void sell() {

        if (TricketNum > 0) {
            TricketNum--;
            System.out.println("还剩票" + TricketNum + "张");
        } else {
            System.out.println("票已经售完！");
            System.exit(0);
        }
    }

    /**
     *当g()运行时，其他对象可以执行
     * 锁的东西不一样，互相不干扰
     */
    public void g(){
        synchronized (new Object()){
            if (TricketNum > 0) {
                TricketNum--;
                System.out.println("还剩票" + TricketNum + "张");
            }
        }

    }
}